<template>
  <div class="edit-popup">
    <popup
      ref="popupRef"
      :title="popupTitle"
      :async="true"
      width="550px"
      @confirm="handleSubmit"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        label-width="84px"
        :rules="formRules"
      >
        <el-form-item label="账号" prop="userName">
          <el-input
            v-model="formData.userName"
            :disabled="isRoot"
            placeholder="请输入账号"
            clearable
          />
        </el-form-item>
        <el-form-item label="头像">
          <div>
            <div>
              <material-picker v-model="formData.avatar" :limit="1" />
            </div>
            <div class="form-tips">
              建议尺寸：100*100px，支持jpg，jpeg，png格式
            </div>
          </div>
        </el-form-item>
        <el-form-item label="名称" prop="nickName">
          <el-input
            v-model="formData.nickName"
            placeholder="请输入名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="请选择岗位" prop="postIds">
          <el-select
            class="flex-1"
            clearable
            multiple
            v-model="formData.postIds"
            placeholder="请选择岗位"
          >
            <el-option
              v-for="(item, index) in optionsData.post"
              :key="index"
              :label="item.postName"
              :value="item.postId"
            />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="归属部门" prop="deptIds">
          <el-tree-select
            class="flex-1"
            v-model="formData.deptIds"
            :data="optionsData.dept"
            clearable
            node-key="id"
            multiple
            :props="{
                            value: 'id',
                            label: 'name',
                            disabled(data: any) {
                                return !!data.isStop
                            }
                        }"
            check-strictly
            :default-expand-all="true"
            placeholder="请选择上级部门"
          />
        </el-form-item> -->
        <el-form-item label="用户类型" prop="userType">
          <el-select
            class="flex-1"
            clearable
            v-model="formData.userType"
            placeholder="请选择用户类型"
          >
            <el-option label="系统用户" value="00" /><el-option
              label="商家用户"
              value="1"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="角色" prop="roleIds">
          <el-select
            v-model="formData.roleIds"
            :disabled="isRoot"
            multiple
            class="flex-1"
            clearable
            placeholder="请选择角色"
          >
            <el-option v-if="isRoot" label="系统管理员" value="0" />
            <el-option
              v-for="(item, index) in optionsData.role"
              :key="index"
              :label="item.roleName"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input
            v-model.trim="formData.phonenumber"
            clearable
            placeholder="手机号"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model.trim="formData.email"
            clearable
            placeholder="邮箱"
          />
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-select
            v-model="formData.sex"
            :disabled="isRoot"
            class="flex-1"
            clearable
            placeholder="请选择性别"
          >
            <el-option
              v-for="(item, index) in sexOptions"
              :key="index"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model.trim="formData.password"
            show-password
            clearable
            placeholder="请输入密码"
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="passwordConfirm">
          <el-input
            v-model.trim="formData.passwordConfirm"
            show-password
            clearable
            placeholder="请输入确认密码"
          />
        </el-form-item>

        <el-form-item label="管理员状态" v-if="!isRoot">
          <el-switch
            v-model="formData.status"
            :active-value="'0'"
            :inactive-value="'1'"
          />
        </el-form-item>

        <el-form-item label="多处登录">
          <div>
            <el-switch
              v-model="formData.isMultipoint"
              :active-value="1"
              :inactive-value="0"
            />
            <div class="form-tips">允许多人同时在线登录</div>
          </div>
        </el-form-item>
      </el-form>
    </popup>
  </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from "element-plus";
import Popup from "@/components/popup/index.vue";
import { adminAdd, adminEdit, adminDetail } from "@/api/perms/admin";
import { useDictOptions } from "@/hooks/useDictOptions";
import { roleAll } from "@/api/perms/role";
import { postAll } from "@/api/org/post";
import { deptListTree } from "@/api/org/department";
import feedback from "@/utils/feedback";
import { sexOptions } from "@/utils/dictUtil";

const emit = defineEmits(["success", "close"]);
const formRef = shallowRef<FormInstance>();
const popupRef = shallowRef<InstanceType<typeof Popup>>();
const mode = ref("add");
const popupTitle = computed(() => {
  return mode.value == "edit" ? "编辑管理员" : "新增管理员";
});

const formData = reactive({
  userId: 0,
  userName: "",
  nickName: "",
  userType: "",
  email: "",
  phonenumber: "",
  deptIds: [],
  postIds: [],
  roleIds: [],
  avatar: "",
  password: "",
  passwordConfirm: "",
  stataus: 0,
});

const isRoot = computed(() => {
  return formData.id == 1;
});

const passwordConfirmValidator = (
  rule: object,
  value: string,
  callback: any
) => {
  if (formData.password) {
    if (!value) callback(new Error("请再次输入密码"));
    if (value !== formData.password) callback(new Error("两次输入密码不一致!"));
  }
  callback();
};

const checkMobile = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback();
  } else {
    const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    console.log(reg.test(value));
    if (reg.test(value)) {
      callback();
    } else {
      return callback(new Error("请输入正确的手机号"));
    }
  }
};
const formRules = reactive({
  userName: [
    {
      required: true,
      message: "请输入账号",
      trigger: ["blur"],
    },
  ],
  nickName: [
    {
      required: true,
      message: "请输入名称",
      trigger: ["blur"],
    },
  ],
  sex: [
    {
      required: true,
      message: "请输入选择性别",
      trigger: ["blur"],
    },
  ],
  phonenumber: [
    {
      required: true,
      message: "请输入手机号",
      trigger: ["blur"],
    },
    {
      validator: checkMobile,
      trigger: ["blur"],
    },
  ],
  roleIds: [
    {
      type: "array",
      required: true,
      message: "请选择角色",
      trigger: ["blur"],
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ] as any[],
  passwordConfirm: [
    {
      required: true,
      message: "请再次输入密码",
      trigger: "blur",
    },
    {
      validator: passwordConfirmValidator,
      trigger: "blur",
    },
  ] as any[],
});

const { optionsData } = useDictOptions<{
  role: any[];
  post: any[];
  //   dept: any[];
}>({
  role: {
    api: roleAll,
  },
  post: {
    api: postAll,
  },
  //   dept: {
  //     api: deptListTree,
  //   },
});

const handleSubmit = async () => {
  await formRef.value?.validate();
  mode.value == "edit" ? await adminEdit(formData) : await adminAdd(formData);
  popupRef.value?.close();
  feedback.msgSuccess("操作成功");
  emit("success");
};

const open = (type = "add") => {
  mode.value = type;
  popupRef.value?.open();
};

const setFormData = async (row: any) => {
  formRules.password = [];
  formRules.passwordConfirm = [
    {
      validator: passwordConfirmValidator,
      trigger: "blur",
    },
  ];
  console.log("row", row);

  const data = await adminDetail(row.userId);
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key];
    }
  }
};

const handleClose = () => {
  emit("close");
};

defineExpose({
  open,
  setFormData,
});
</script>
